"""
插件测试工具
用于自动化测试插件的功能和性能
"""

import asyncio
import logging
import json
import time
from typing import Dict, Any, List, Optional
from src.plugins.plugin_manager import UnifiedPluginManager
from src.tools.plugin_debugger import PluginDebugger


class PluginTester:
    """插件测试器"""
    
    def __init__(self):
        self.plugin_manager = UnifiedPluginManager()
        self.debugger = PluginDebugger()
        self.logger = logging.getLogger(__name__)
    
    async def run_all_tests(self, plugin_name: str, test_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        运行所有测试
        
        Args:
            plugin_name: 插件名称
            test_config: 测试配置
            
        Returns:
            测试结果
        """
        if test_config is None:
            test_config = {}
        
        results = {
            "plugin_name": plugin_name,
            "timestamp": time.time(),
            "tests": {},
            "summary": {}
        }
        
        # 运行功能测试
        functional_test_result = await self.run_functional_test(plugin_name, test_config)
        results["tests"]["functional"] = functional_test_result
        
        # 运行性能测试
        performance_test_result = await self.run_performance_test(plugin_name, test_config)
        results["tests"]["performance"] = performance_test_result
        
        # 运行稳定性测试
        stability_test_result = await self.run_stability_test(plugin_name, test_config)
        results["tests"]["stability"] = stability_test_result
        
        # 生成测试摘要
        results["summary"] = self._generate_test_summary(results["tests"])
        
        return results
    
    async def run_functional_test(self, plugin_name: str, test_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        运行功能测试
        
        Args:
            plugin_name: 插件名称
            test_config: 测试配置
            
        Returns:
            测试结果
        """
        result = {
            "name": "functional_test",
            "passed": False,
            "details": {},
            "execution_time": 0
        }
        
        start_time = time.time()
        try:
            # 使用调试器进行功能测试
            test_data = test_config.get("test_data")
            debug_result = await self.debugger.debug_plugin(plugin_name, test_data)
            
            result["details"] = debug_result
            result["passed"] = debug_result.get("success", False)
            
        except Exception as e:
            result["details"]["error"] = f"功能测试执行失败: {str(e)}"
            self.logger.error(f"功能测试 {plugin_name} 失败: {e}")
        
        result["execution_time"] = time.time() - start_time
        return result
    
    async def run_performance_test(self, plugin_name: str, test_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        运行性能测试
        
        Args:
            plugin_name: 插件名称
            test_config: 测试配置
            
        Returns:
            测试结果
        """
        result = {
            "name": "performance_test",
            "passed": True,  # 默认通过，除非有明确的性能问题
            "details": {},
            "execution_time": 0
        }
        
        start_time = time.time()
        try:
            # 获取性能测试配置
            iterations = test_config.get("performance", {}).get("iterations", 10)
            max_execution_time = test_config.get("performance", {}).get("max_execution_time", 5.0)
            
            # 运行多次测试以评估性能
            execution_times = []
            test_data = test_config.get("test_data")
            
            for i in range(iterations):
                iter_start_time = time.time()
                try:
                    await self.debugger.debug_plugin(plugin_name, test_data)
                except Exception as e:
                    self.logger.warning(f"性能测试第 {i+1} 次迭代失败: {e}")
                iter_end_time = time.time()
                execution_times.append(iter_end_time - iter_start_time)
            
            # 计算性能指标
            if execution_times:
                avg_time = sum(execution_times) / len(execution_times)
                min_time = min(execution_times)
                max_time = max(execution_times)
                
                result["details"] = {
                    "iterations": iterations,
                    "average_execution_time": avg_time,
                    "min_execution_time": min_time,
                    "max_execution_time": max_time,
                    "total_time": sum(execution_times)
                }
                
                # 检查是否超过最大执行时间
                if avg_time > max_execution_time:
                    result["passed"] = False
                    result["details"]["warning"] = f"平均执行时间 {avg_time:.4f}s 超过阈值 {max_execution_time}s"
            else:
                result["details"]["error"] = "没有成功执行的测试"
                result["passed"] = False
                
        except Exception as e:
            result["details"]["error"] = f"性能测试执行失败: {str(e)}"
            result["passed"] = False
            self.logger.error(f"性能测试 {plugin_name} 失败: {e}")
        
        result["execution_time"] = time.time() - start_time
        return result
    
    async def run_stability_test(self, plugin_name: str, test_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        运行稳定性测试
        
        Args:
            plugin_name: 插件名称
            test_config: 测试配置
            
        Returns:
            测试结果
        """
        result = {
            "name": "stability_test",
            "passed": True,
            "details": {},
            "execution_time": 0
        }
        
        start_time = time.time()
        try:
            # 运行生命周期测试
            lifecycle_result = await self.debugger.test_plugin_lifecycle(plugin_name)
            
            result["details"] = lifecycle_result
            result["passed"] = lifecycle_result.get("success", False)
            
        except Exception as e:
            result["details"]["error"] = f"稳定性测试执行失败: {str(e)}"
            result["passed"] = False
            self.logger.error(f"稳定性测试 {plugin_name} 失败: {e}")
        
        result["execution_time"] = time.time() - start_time
        return result
    
    def _generate_test_summary(self, test_results: Dict[str, Any]) -> Dict[str, Any]:
        """
        生成测试摘要
        
        Args:
            test_results: 测试结果
            
        Returns:
            测试摘要
        """
        summary = {
            "total_tests": 0,
            "passed_tests": 0,
            "failed_tests": 0,
            "pass_rate": 0.0,
            "total_execution_time": 0.0
        }
        
        for test_name, test_result in test_results.items():
            summary["total_tests"] += 1
            if test_result.get("passed", False):
                summary["passed_tests"] += 1
            else:
                summary["failed_tests"] += 1
            summary["total_execution_time"] += test_result.get("execution_time", 0)
        
        if summary["total_tests"] > 0:
            summary["pass_rate"] = summary["passed_tests"] / summary["total_tests"]
        
        return summary
    
    def export_test_report(self, test_results: Dict[str, Any], format: str = "json") -> str:
        """
        导出测试报告
        
        Args:
            test_results: 测试结果
            format: 报告格式 (json, text)
            
        Returns:
            报告内容
        """
        if format == "json":
            return json.dumps(test_results, ensure_ascii=False, indent=2)
        elif format == "text":
            return self._generate_text_report(test_results)
        else:
            raise ValueError(f"不支持的报告格式: {format}")
    
    def _generate_text_report(self, test_results: Dict[str, Any]) -> str:
        """
        生成文本格式测试报告
        
        Args:
            test_results: 测试结果
            
        Returns:
            文本报告
        """
        report = []
        report.append("=" * 50)
        report.append("插件测试报告")
        report.append("=" * 50)
        report.append(f"插件名称: {test_results.get('plugin_name', 'Unknown')}")
        report.append(f"测试时间: {test_results.get('timestamp', 'Unknown')}")
        report.append("")
        
        # 测试摘要
        summary = test_results.get("summary", {})
        report.append("测试摘要:")
        report.append(f"  总测试数: {summary.get('total_tests', 0)}")
        report.append(f"  通过测试: {summary.get('passed_tests', 0)}")
        report.append(f"  失败测试: {summary.get('failed_tests', 0)}")
        report.append(f"  通过率: {summary.get('pass_rate', 0)*100:.2f}%")
        report.append(f"  总执行时间: {summary.get('total_execution_time', 0):.4f}s")
        report.append("")
        
        # 详细测试结果
        report.append("详细测试结果:")
        for test_name, test_result in test_results.get("tests", {}).items():
            report.append(f"  {test_name}:")
            report.append(f"    通过: {'是' if test_result.get('passed', False) else '否'}")
            report.append(f"    执行时间: {test_result.get('execution_time', 0):.4f}s")
            
            # 添加详细信息
            details = test_result.get('details', {})
            if 'error' in details:
                report.append(f"    错误: {details['error']}")
            report.append("")
        
        return "\n".join(report)


async def main():
    """测试器主函数示例"""
    tester = PluginTester()
    
    # 示例：运行所有测试
    # test_config = {
    #     "test_data": {"action": "list", "path": "."},
    #     "performance": {
    #         "iterations": 5,
    #         "max_execution_time": 2.0
    #     }
    # }
    # 
    # results = await tester.run_all_tests("filesystem", test_config)
    # 
    # # 导出JSON报告
    # json_report = tester.export_test_report(results, "json")
    # print(json_report)
    # 
    # # 导出文本报告
    # text_report = tester.export_test_report(results, "text")
    # print(text_report)


if __name__ == "__main__":
    asyncio.run(main())